import { useKeyPress } from "ahooks";
import {
  copySelectedComponent,
  pasteCopiedComponent,
  removeSelectedComponent,
  selectNextComponent,
  selectPrevComponent,
} from "../store/componentsReducer";
import { useDispatch } from "react-redux";
import { ActionCreators as UndoActionCreators } from "redux-undo";

function isActiveElementValid() {
  const activeElement = document.activeElement;
  //没有增加dnd-kit之前
  // if (activeElement === document.body) return true;
  if (activeElement === document.body) return true;
  if (activeElement?.matches('div[role="button"')) return true;

  return false;
}

function useBindCanvasKeyPress() {
  const dispatch = useDispatch();
  //删除组件
  useKeyPress(["backspace", "delete"], () => {
    if (!isActiveElementValid()) return;
    dispatch(removeSelectedComponent());
  });

  //复制组件
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid()) return;
    dispatch(copySelectedComponent());
  });

  //粘贴组件
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementValid()) return;
    dispatch(pasteCopiedComponent());
  });

  //选中上一个
  useKeyPress("uparrow", () => {
    dispatch(selectPrevComponent());
  });

  //选中下一个
  useKeyPress("downarrow", () => {
    dispatch(selectNextComponent());
  });

  ///撤销/重做
  useKeyPress(
    ["ctrl.z", "meta.z"],
    () => {
      dispatch(UndoActionCreators.undo());
    },
    {
      exactMatch: true,
    }
  );
  useKeyPress(
    ["ctrl.shift.z", "meta.shift.z"],
    () => {
      dispatch(UndoActionCreators.redo());
    },
    {
      exactMatch: true,
    }
  );
}

export default useBindCanvasKeyPress;
